<?php

class PapiWS_Model_ShapeRenderer {
	
	// Imagemagick image
	public $canvas = null; 


	public function __construct( $image )
	{
		$this->canvas = $image;
	}

	public function render( $shape ) {

		$shapeFile = tempnam( "/tmp", "shaperend" );
		$isUserImage = false;
		if ( isset( $shape->svgUrl))
			$stat = copy($shape->svgUrl, $shapeFile);
		else if ( isset( $shape->swfUrl ) ) {
			$isUserImage = true;
			$stat = copy($shape->swfUrl, $shapeFile);
		} else {
			error_log( "No SVG or PNG found in shape." );
			return;
		}
		if ( $stat === false ) {
			error_log( "Copying from $shape->svgUrl -> $shapeFile failed" );
			die('Copy failed.');
		}

		$shapeImage = new Imagick();
		$shapeImage->setResolution( 300, 300 );
		$shapeImage->setBackgroundColor( 'transparent' );
		$shapeImage->readImage( $shapeFile  );


		// resize
		$shapeImage->scaleImage( 
			$this->mmToPx($shape->width),
			$this->mmToPx($shape->height)
		);

		$affine = new PapiWS_Model_AffineTransformation();
		$affine->rotate( $shape->angle );
		$affine->translate(
			$this->mmToPx($shape->x), 
			$this->mmToPx($shape->y)
		);

		$draw = new ImagickDraw();
		$draw->affine( $affine->getCurrentMatrix() );

		if ( $shape->hasDropShadow ) {
			$shadow = $shapeImage->clone();
			$shadow->shadowImage( 50, 2, 0, 0 );
			$draw->composite( Imagick::COMPOSITE_OVER, 0, 0, 0, 0, $shadow);
			$this->canvas->drawImage( $draw );
		}

		if ( $isUserImage ) {
			$shapeImage->setImageOpacity($shape->alpha);
		} else {
			$rgbColor = sprintf( "#%06x", $shape->tint );
			$shapeImage->paintOpaqueImage('black', $rgbColor, 10);
		}

		$draw->composite( Imagick::COMPOSITE_OVER, 0, 0, 0, 0, $shapeImage);

		$this->canvas->drawImage( $draw );

		// cleanup 
		unlink( $shapeFile );
	}

	// TODO: Mover esto a otro lado.
    function mmToPx( $length )
    {
        // TODO get from conf. Take into account
        // the fact that output DPI != input DPI !!!!
        $dpi = 200;
        $lengthPx = $length * $dpi / 25.4;
        return (int) round( $lengthPx );
    }
}
